from scipy.optimize import curve_fit
import numpy as np
from sqlalchemy import text
from db.mysqlconn import getMySession,myeng,mydbkey
import matplotlib.pyplot as plt
 # 创建一个函数模型用来生成数据
def funsig(x, a, b1, b2, c):
    #r = a * np.exp(-((x[0] - b) ** 2 + (x[1] - d) ** 2) / (2 * c ** 2))
    r= a / (1 + np.exp(-b1*x[0]-b2*x[1]+c))
    if isinstance(r, np.ndarray) :
        return r.ravel()
    else:
        return r
 
def fit(name,xx,z):
    abcd, para = curve_fit(funsig, xx, z) 
    engine,session,Base,classes=mydbkey()
    
    t_fun =  classes.t_fun
    session.execute( text("delete from  t_fun where name=:name "),{"name":name })
    ix=0
    for a in abcd:
        session.add(t_fun(name=name,rat=a,idx=ix))
        ix=ix+1
    session.commit(  )
    session.close()
    return abcd, para

def getfun(name):
    engine,session,Base,classes=mydbkey()
    t_fun =  classes.t_fun
    res=session.query(t_fun).filter(t_fun.name==name).all()

def funcall(name,xx):
    engine,session,Base,classes=mydbkey()
    t_fun =  classes.t_fun
    res=session.query(t_fun).filter(t_fun.name==name).order_by(t_fun.idx).all()
    abcd=[]
    for r in res:
        abcd.append(r.rat)
    print(abcd)
    Z = funsig(xx, *abcd)
    return Z;

def test():
    xx = np.indices([10, 10])
    #y_data = sigmoid_fit(x_data,4,0.2,0.4,0.5) + np.random.normal(size=100)/100 
   # z = funsig(xx, 10, 5, 2, 5) + np.random.normal(size=100)/100 
    z = funsig(xx, 4,0.2,0.4,0.5) + np.random.normal(size=100)/100 
    abcd, para = fit("fun1", xx, z)
    print(abcd)
    Z=funcall("fun1",xx)
    print(Z)
    z=z.reshape(10,10)
    Z=Z.reshape(10,10)
    ax = plt.subplot(projection='3d')
    ax.scatter3D(xx[0], xx[1], z, color='red')
    ax.plot_surface(xx[0], xx[1], Z, cmap='rainbow')
    plt.show()  

def test2():
    xx = np.indices([1, 1])
    xx=[9,10]
    print(xx)
    z=funcall("fun1",xx)
    print(z)
    return z
 


